package drawing;

import java.util.ArrayList;
import java.util.HashMap;

import math.Color3f;
import math.Point3f;
import math.Triangle;
import math.Vector3f;

public class Scene {

	private HashMap<String, Camera> cameras;
	private HashMap<String, PointLight> pointLights;
	private HashMap<String, DiffuseMaterial> diffuseMaterials;
	private ArrayList<Triangle> triangles;
	private Camera currentCamera;
	private ArrayList<String> currentLights;
	private Color3f backgroundColor;

	public Scene() {
		initializeDatastructures();
	}

	private void initializeDatastructures() {
		cameras = new HashMap<String, Camera>();
		pointLights = new HashMap<String, PointLight>();
		currentLights = new ArrayList<String>();
		diffuseMaterials = new HashMap<String, DiffuseMaterial>();
		triangles = new ArrayList<Triangle>();
	}

	public void addCamera(Camera camera) {
		this.cameras.put(camera.getName(), camera);
	}

	public void addPointLight(PointLight light) {
		this.pointLights.put(light.getName(), light);
	}

	public void addTriangles(ArrayList<Triangle> triangles) {
		this.triangles.addAll(triangles);
	}

	public void setCurrentCamera(String name) {
		this.currentCamera = this.cameras.get(name);
	}

	public Camera getCurrentCamera() {
		return this.currentCamera;
	}

	public void setBackgroundColor(Color3f color) {
		this.backgroundColor = color;
	}

	public Color3f getBackgroundColor() {
		return this.backgroundColor;
	}

	public ArrayList<Triangle> getTriangles() {
		return this.triangles;
	}

	public void addDiffuseMaterial(DiffuseMaterial material) {
		this.diffuseMaterials.put(material.getName(), material);
	}

	public void setCurrentLights(String[] lightNames) {
		this.currentLights.clear();
		for (int i = 0; i < lightNames.length; i++) {
			this.currentLights.add(lightNames[i]);
		}
	}

	public Color3f getColor(HitRecord record) {
		Color3f result;
		PointLight pointLight = this.pointLights.get(this.currentLights.get(0));
		Color3f materialColor = this.diffuseMaterials.get("dif0").getColor();
		result = pointLight.getColor().scale(pointLight.getIntensity());
		result = result.multiply(materialColor);
		
		Vector3f normal = record.getNormal();
		Point3f origin = record.getRay().getOrigin();
		Vector3f direction = record.getRay().getDirection();
		
		Point3f hitPoint;
		Vector3f tempVector = new Vector3f(direction.x - origin.x, direction.y - origin.y, direction.z - origin.z);
		tempVector.scale(record.getT());
		hitPoint = new Point3f(origin.x + tempVector.x, origin.y + tempVector.y, origin.z + tempVector.z);
		
		Vector3f lightVector = new Vector3f(pointLight.getPosition().x - hitPoint.x, pointLight.getPosition().y - hitPoint.y, pointLight.getPosition().z - hitPoint.z);
//		lightVector = lightVector.scale(1.0f/lightVector.length());
		
		float temp = normal.dotProduct(lightVector);
		temp = Math.max(0, -temp);
		result = result.scale(temp);
		result = result.clip();
		return result;
	}
}
